<template>
  <div>
    <van-nav-bar
      :title="generateTitle($route.name,$route.params.title||$route.meta.title)"
      :left-text="$t('back')"
      :right-text="rightText"
      left-arrow
      fixed
      @click-left="$router.push({ name: 'dashboard' })"
      @click-right="toCheckMode()"
    />
    <van-search
      v-model="subject"
      @search="onSearch"
    />
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        @load="onLoad">
        <card-list
          v-for="(item,index) in list"
          :key="item.id+index"
          :title="item.procDefName"
          :desc="item.subject"
          :date="item.createTime|formatTime"
          :tag="_getStatus(item.status)"
          :tag-type="_getStatusType(item.status)"
          :bg-color="_randomColor(index)"
          :icon="_randomIcon(index)"
          :check-mode="checkMode"
          :checked="checkedIds.includes(item.id)"
          is-link
          @click="onClick(item)"/>
      </van-list>
      <list-result-page
        :result-type="resultType"
        :error-type="errorType"
        :result-message="resultMessage"/>
    </van-pull-refresh>
    <lc-toolbar
      v-show="checkMode"
      :actions="actions"/>
    <batch-popup
      v-model="batchOpinionPopup"
      :task-id="checkedIds"
      :action-name="actionName"
      @on-refresh="onRefreshPage"
    />
  </div>
</template>
<script>
import LcToolbar from '@/components/LcToolbar'
import CardList from '@/components/CardList'
import ListResultPage from '@/components/ListResultPage'

import { myTasks } from '@/api/platform/bpmn/bpmn'
import { batchSuspendProcess, batchRecoverProcess } from '@/api/platform/bpmn/action'

import { formatParams, loadFinished, getResultType } from '@/utils/params'
import random from '@/mixins/random'
import bpmnStatus from '@/mixins/bpmnStatus'
import i18n from '@/utils/i18n'
import BatchPopup from './batch'

export default {
  components: {
    CardList,
    ListResultPage,
    LcToolbar,
    BatchPopup
  },
  mixins: [random, bpmnStatus],
  data() {
    return {
      subject: '',
      list: [],
      page: 1,
      loading: false,
      finished: false,
      isLoading: true,
      resultType: 'init',
      errorType: null,
      resultMessage: null,
      checkMode: false,
      checkedIds: [],
      show: false,
      actions: [
        {
          name: this.$t('common.button.agree'),
          callback: this.openAgreeDialog
        }, {
          name: this.$t('common.button.stop'),
          callback: this.openStopDialog
        }, {
          name: this.$t('common.button.suspend'),
          callback: this.suspend
        }, {
          name: this.$t('common.button.recover'),
          callback: this.recover
        }
      ],
      batchOpinionPopup: false,
      actionName: 'agree'
    }
  },
  computed: {
    rightText() {
      if (this.list.length > 0) {
        return this.checkMode ? this.$t('common.button.cancel') : this.$t('common.button.manage')
      }
      return null
    }
  },
  methods: {
    generateTitle(name, title) { // generateTitle by vue-i18n
      return i18n.generateTitle(name, title)
    },
    getData() {
      const params = formatParams({ 'Q^subject_^SL': this.subject }, { 'page': this.page })
      myTasks(params).then(response => {
        if (this.$utils.isNotEmpty(response.data.dataResult)) {
          this.page++
          this.list = this.list.concat(response.data.dataResult)
          this.finished = false
        }
        this.finished = !!loadFinished(response.data.pageResult)
        this.loading = false
        this.isLoading = false
        // 结果类型
        this.resultType = getResultType(this.list, this.finished)
      }).catch((e) => {
        this.loading = false
        this.isLoading = false
        this.finished = true
        this.resultType = 'error'
        this.resultMessage = e.message
      })
    },
    onSearch() {
      this.resultType = 'init'
      this.page = 1
      this.list = []
      this.getData()
    },
    onLoad() {
      this.getData()
    },
    onRefresh() {
      this.resultType = 'init'
      this.isLoading = true
      this.page = 1
      this.list = []
      this.getData()
    },
    onRefreshPage() {
      this.checkMode = false
      this.onRefresh()
    },
    onClick(item) {
      if (this.checkMode) {
        const index = this.checkedIds.indexOf(item.id)
        if (index > -1) {
          this.checkedIds.splice(index, 1)
        } else {
          this.checkedIds.push(item.id)
        }
      } else {
        this.$router.push({
          name: 'bpmnForm',
          query: {
            taskId: item.id
          },
          params: {
            title: item.procDefName
          }
        })
      }
    },
    toCheckMode() {
      if (this.checkMode) {
        this.show = true
      }
      this.checkMode = !this.checkMode
    },
    openAgreeDialog() {
      if (this.checkedIds.length === 0) {
        return this.$toast(this.$t('common.dialog.selectedRecords'))
      }
      this.batchOpinionPopup = true
      this.actionName = 'agree'
    },
    openStopDialog() {
      if (this.checkedIds.length === 0) {
        return this.$toast(this.$t('common.dialog.selectedRecords'))
      }
      this.batchOpinionPopup = true
      this.actionName = 'stop'
    },
    suspend() {
      if (this.checkedIds.length === 0) {
        return this.$toast(this.$t('common.dialog.selectedRecords'))
      }
      this.$dialog.confirm({
        title: this.$t('common.dialog.warn'),
        message: this.$t('common.operate.makeSure')
      }).then(() => {
        const taskIds = this.checkedIds.join()
        batchSuspendProcess({ 'taskIds': taskIds }).then(response => {
          this.$toast.success(`批量挂起流程成功！`)
          this.onRefreshPage()
        }).catch((e) => {
          console.error(e)
        })
      })
    },
    recover() {
      if (this.checkedIds.length === 0) {
        return this.$toast(this.$t('common.dialog.selectedRecords'))
      }
      this.$dialog.confirm({
        title: this.$t('common.dialog.warn'),
        message: this.$t('common.operate.makeSure')
      }).then(() => {
        const taskIds = this.checkedIds.join()
        batchRecoverProcess({ 'taskIds': taskIds }).then(response => {
          this.$toast.success(`批量恢复流程成功！`)
          this.onRefreshPage()
        }).catch((e) => {
          console.error(e)
        })
      })
    }
  }

}
</script>
